package com.steadyoung.modelapp.rxretrofit.http;


import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/9/13.
 * Email : steadyoung@foxmail.com
 * Auth  : wayne
 * Desc  : 拦截器
 */
public class TokenInterceptor implements Interceptor {

    private static final String TOKEN_KEY = "token";

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request originalRequest = chain.request();
//        String token = AppData.getInstance().getToken();
////        LogUtils.d("TokenInterceptor_start>>>>token:" + token );
//        if (TextUtils.isEmpty(token) || alreadyHasAuthorizationHeader(originalRequest,token)) {
//            return chain.proceed(originalRequest);
//        }
        Request authorised = originalRequest.newBuilder()
//                .header(TOKEN_KEY, token)
                .build();
//        LogUtils.d("token》》》" + token);
        return chain.proceed(authorised);
    }

    /**
     *
     * @param request
     * @param token
     * @return
     */
    public static boolean alreadyHasAuthorizationHeader(Request request,String token) {
        if (request != null) {
            if (request.headers() != null) {

                String tk = request.headers().get(TOKEN_KEY);//获取请求头中的token
//                String tk1 =  request.header(TOKEN_KEY);//获取请求头中的token
                if(token.equals(tk)){
                    return true;
                }else{
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }
}
